package View;

import Controller.UserController;
import pojo.AppData;
import pojo.Car;
import pojo.Customer;
import pojo.RentalRecord;

import javax.sql.rowset.CachedRowSet;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.swing.event.AncestorListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

public class UserVehicleWindow {

    private UserController userController;

    {
        try {
            userController = new UserController();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private JFrame frame = new JFrame("车辆浏览和租车还车管理");
    private JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);

    private JPanel controlPanel = new JPanel();
    private JPanel displayPanel = new JPanel();

    private JButton returnBRoseButton = new JButton("还车界面");
    private JButton rentRoseButton = new JButton("租车界面");
    private JButton rentButtons = new JButton("租车");
    public int tableflag = -1;


    JLabel labelBrand = new JLabel("车辆品牌:");
    JTextField brandTextField = new JTextField(10);
    JButton vehicleSearchButton = new JButton("查询车辆");

    JLabel labelCarId = new JLabel("车辆品牌:");
    JTextField CarIdTextField = new JTextField(10);
    JButton returnButton = new JButton("还车");

    private JButton vehicleShowButton = new JButton("车辆展示");
    private JButton returnMain_windowButton = new JButton("返回主窗口");

    private JTable browseTable = new JTable();
    private JTable rentalTable = new JTable();

    public UserVehicleWindow(UserMain_window userMainWindow) {
        frameControl(userMainWindow);
    }


public void frameControl(UserMain_window userMainWindow) {
    frame.setSize(800, 400);
    frame.setLocation(200, 200);
    frame.setResizable(false);

    controlPanel.setLayout(new BoxLayout(controlPanel, BoxLayout.Y_AXIS));
    Dimension buttonSize = new Dimension(100, 30);
    returnBRoseButton.setPreferredSize(buttonSize);
    returnButton.setPreferredSize(buttonSize);
    rentRoseButton.setPreferredSize(buttonSize);
    rentButtons.setPreferredSize(buttonSize);
    vehicleSearchButton.setPreferredSize(buttonSize);
    vehicleShowButton.setPreferredSize(buttonSize);
    returnMain_windowButton.setPreferredSize(buttonSize);

    controlPanel.add(rentRoseButton);
    controlPanel.add(returnBRoseButton);
    controlPanel.add(vehicleShowButton);
    controlPanel.add(returnMain_windowButton);

    displayPanel.setLayout(new BorderLayout());
    splitPane.setLeftComponent(controlPanel);
    splitPane.setRightComponent(displayPanel);

    // 设置右边面板默认展开，这里设置为 100 像素
    splitPane.setDividerLocation(100);

    frame.add(splitPane);

    setButtonActions(userMainWindow);

    frame.setVisible(true);
}




    private void setButtonActions(UserMain_window userMainWindow) {

        rentRoseButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 处理车辆展示按钮点击事件，例如更新右侧面板内容
                VehicleModelDB vehicleModelDB = new VehicleModelDB();
                JTable table = new JTable(vehicleModelDB);

                // 创建一个用于条件查询还车的面板
                JPanel rentPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
                JLabel label = new JLabel("暂时未选中租车信息");

                rentPanel.add(label);
                rentPanel.add(rentButtons);

                // 使用selection监听器来监听table的哪个条目被选中
                table.getSelectionModel().addListSelectionListener(
                        new ListSelectionListener() {

                            // 当选择了某一行的时候触发该事件
                            @Override
                            public void valueChanged(ListSelectionEvent e) {
                                // 获取哪一行被选中了
                                int row = table.getSelectedRow();
                                // 根据选中的行，到VehicleModelDB中获取对应的对象
                                Car car = VehicleModelDB.cars.get(row);
                                // 更新标签内容
                                tableflag = row;

                                label.setText("当前选中的车辆ID："+car.getCar_id() +", 品牌："+car.getBrand()+", 租金：" + car.getRental_rate()+", 车辆状态："+car.getStatus());

                                rentButtons.addActionListener(new ActionListener() {
                                    @Override
                                    public void actionPerformed(ActionEvent e) {
                                        int selectedRow = table.getSelectedRow();
                                        if (selectedRow >= 0) {
                                            int carId = (int)table.getValueAt(selectedRow, 0);
                                            String carModel = table.getValueAt(selectedRow, 1).toString();
                                            String carBrand = table.getValueAt(selectedRow, 2).toString();
                                            String carLicense_plate = table.getValueAt(selectedRow, 3).toString();
                                            String carStatus = table.getValueAt(selectedRow, 4).toString();
                                            int carFee = (int) table.getValueAt(selectedRow,5);
                                            String type = table.getValueAt(selectedRow,6).toString();
                                            String color = table.getValueAt(selectedRow,7).toString();
                                            int mili = (int) table.getValueAt(selectedRow,8);

                                            Car car1 = new Car(carId, carModel, carBrand, carLicense_plate, carStatus, carFee,type, color, mili);

                                            if(tableflag>=0){
                                                if(carStatus.equals("已租")){
                                                    String message = String.format("车辆ID: %s\n 车辆型号：%s\n 品牌: %s\n车牌号: %s\n不可以租！已在租赁中！！", carId, carModel,carBrand, carLicense_plate);
                                                    JOptionPane.showMessageDialog(null, message);
                                                }
                                                //进行数据库修改车辆和状态和增加订单，个人信息的修改
                                                if (carStatus.equals("可租")){
                                                    try {
                                                        //更新车辆信息
                                                        userController.updateByCar(car);
                                                        //更新订单信息
                                                        userController.updateRentalRecord(carId,AppData.getUserId());
                                                        //更新个人信息
                                                        Customer customer = userController.getCustomerById(AppData.getUserId());
                                                        userController.updateUserByRent(customer);
                                                    } catch (Exception exception) {
                                                        exception.printStackTrace();
                                                    }

                                                    String message = String.format("车辆ID: %s\n 车辆型号：%s\n 品牌: %s\n车牌号: %s\n已被您租用！！！",  carId, carModel,carBrand, carLicense_plate);
                                                    JOptionPane.showMessageDialog(null, message);
                                                }
                                                if (carStatus.equals("维护中")){
                                                    String message = String.format("车辆ID: %s\n 车辆型号：%s\n 品牌: %s\n车牌号: %s\n不可以租！正在维修中！！", carId, carModel,carBrand, carLicense_plate);
                                                    JOptionPane.showMessageDialog(null, message);
                                                }
                                            }

                                            tableflag = -1;

                                            displayPanel.removeAll();
                                            displayPanel.add(new JScrollPane(table), BorderLayout.CENTER);
                                            displayPanel.add(rentPanel,BorderLayout.NORTH);
                                            displayPanel.revalidate();
                                            displayPanel.repaint();

                                        } else {
                                            JOptionPane.showMessageDialog(null, "请选择要还车的订单");
                                        }

                                    }
                                });

                            }
                        });


                displayPanel.removeAll();
                displayPanel.add(new JScrollPane(table), BorderLayout.CENTER);
                displayPanel.add(rentPanel,BorderLayout.NORTH);
                displayPanel.revalidate();
                displayPanel.repaint();
            }
        });

        returnBRoseButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                // 处理车辆还车按钮点击事件，例如更新右侧面板内容
                RentalVehicleModelDB rentalVehicleModelDB = new RentalVehicleModelDB();
                JTable table = new JTable(rentalVehicleModelDB);

                // 创建一个用于条件查询还车的面板
                JPanel returnPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
                JLabel label = new JLabel("暂时没有还车订单");

                returnPanel.add(label);
                returnPanel.add(returnButton);
                // 使用selection监听器来监听table的哪个条目被选中
                table.getSelectionModel().addListSelectionListener(
                        new ListSelectionListener() {

                            // 当选择了某一行的时候触发该事件
                            @Override
                            public void valueChanged(ListSelectionEvent e) {
                                // 获取哪一行被选中了
                                int row = table.getSelectedRow();
                                // 根据选中的行，到HeroTableModel中获取对应的对象
                                RentalRecord order = rentalVehicleModelDB.orders.get(row);
                                // 更新标签内容
                                tableflag = row;
                                label.setText("当前选中的订单ID："+order.getRecord_id() +", 车辆ID："+order.getCar_id()+", 费用：" + order.getRental_fee());

                                returnButton.addActionListener(new ActionListener() {
                                    @Override
                                    public void actionPerformed(ActionEvent e) {
                                        int selectedRow = table.getSelectedRow();
                                        if (selectedRow >= 0) {
                                            int orderId = (int)table.getValueAt(selectedRow, 0);
                                            int vehicleId = (int)table.getValueAt(selectedRow, 1);
                                            String orderStatus = table.getValueAt(selectedRow, 2).toString();
                                            String rentalFee = table.getValueAt(selectedRow, 3).toString();
                                            String rentalDays = table.getValueAt(selectedRow, 4).toString();

                                            if (tableflag>=0){
                                                //还车进行数据库修改订单状态
                                                if(orderStatus.equals("进行中")){
                                                    try {
                                                        //订单状态,车辆修改
                                                        userController.updateRentalRecord(order);
                                                        //更新个人信息
                                                        Customer customer = userController.getCustomerById(AppData.getUserId());
                                                        userController.updateUserByReturn(customer,order);
                                                    } catch (Exception exception) {
                                                        exception.printStackTrace();
                                                    }
                                                    String message = String.format("订单ID: %s\n车辆ID: %s\n订单天数: %s\n租金: %s\n还车成功！", orderId, vehicleId,rentalDays, rentalFee);
                                                    JOptionPane.showMessageDialog(null, message);
                                                }
                                                if (orderStatus.equals("已完成")){
                                                    String message = String.format("订单ID: %s\n车辆ID: %s\n已完成！！！", orderId, vehicleId);
                                                    JOptionPane.showMessageDialog(null, message);
                                                }
                                                if (orderStatus.equals("已取消")){
                                                    String message = String.format("订单ID: %s\n车辆ID: %s\n已取消不需要点击！！！", orderId, vehicleId);
                                                    JOptionPane.showMessageDialog(null, message);
                                                }
                                            }
                                            tableflag = -1;
                                            displayPanel.removeAll();
                                            displayPanel.add(new JScrollPane(table), BorderLayout.CENTER);
                                            displayPanel.add(returnPanel,BorderLayout.NORTH);
                                            displayPanel.revalidate();
                                            displayPanel.repaint();

                                        } else {
                                            JOptionPane.showMessageDialog(null, "请选择要还车的订单");
                                        }

                                    }
                                });

                            }
                        });

                displayPanel.removeAll();
                displayPanel.add(new JScrollPane(table), BorderLayout.CENTER);
                displayPanel.add(returnPanel,BorderLayout.NORTH);
                displayPanel.revalidate();
                displayPanel.repaint();

            }
        });

        //车辆查询按钮事件
        vehicleSearchButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String searchText = brandTextField.getText();
                if (searchText.equals("")) {
                    JOptionPane.showMessageDialog(null, "请选择要查询的车辆");
                } else {
                    //查询成功
                    JOptionPane.showMessageDialog(null, "查询成功！");
                    // 处理车辆展示按钮点击事件，例如更新右侧面板内容
                    VehicleModelDB vehicleModelDB = new VehicleModelDB(searchText);
                    JTable table = new JTable(vehicleModelDB);

                    // 创建一个用于条件查询的面板
                    JPanel searchPanel = createSearchPanel(labelBrand,brandTextField,vehicleSearchButton);

                    displayPanel.removeAll();
                    displayPanel.add(new JScrollPane(table), BorderLayout.CENTER);
                    displayPanel.add(searchPanel,BorderLayout.NORTH);
                    displayPanel.revalidate();
                    displayPanel.repaint();
                }
            }
        });

        //车辆展示按钮事件
        vehicleShowButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 处理车辆展示按钮点击事件，例如更新右侧面板内容
                VehicleModelDB vehicleModelDB = new VehicleModelDB();
                JTable table = new JTable(vehicleModelDB);

                // 创建一个用于条件查询的面板
                JPanel searchPanel = createSearchPanel(labelBrand,brandTextField,vehicleSearchButton);

                displayPanel.removeAll();
                displayPanel.add(new JScrollPane(table), BorderLayout.CENTER);
                displayPanel.add(searchPanel,BorderLayout.NORTH);
                displayPanel.revalidate();
                displayPanel.repaint();
            }
        });

        //返回用户主窗口按钮
        returnMain_windowButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                frame.setVisible(false);
                userMainWindow.frame.setVisible(true);
            }
        });
    }

    private JPanel createSearchPanel(JLabel label,JTextField textField,JButton button) {
        JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        searchPanel.add(label);
        searchPanel.add(textField);
        searchPanel.add(button);

        return searchPanel;
    }
    // 获取当前时间
    private String getCurrentTimestamp() {
        // 获取当前时间
        Date d = new Date();

        long time = d.getTime();

        // 2、格式化日期对象，和时间 毫秒值。
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formattedTimestamp = dateFormat.format(time);

        return formattedTimestamp;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            UserVehicleWindow userVehicleWindow = new UserVehicleWindow(new UserMain_window());
        });
    }
}
